﻿using System.Text;

namespace Gamey
{
    public class FieldReader
    {
        public FieldReader(int offset, int length, char[] specialCharacters = null)
        {
            Offset = offset;
            Length = length;
            SpecialCharacters = specialCharacters;
        }

        public int Offset { get; protected set; }
        public int Length { get; protected set; }
        public char[] SpecialCharacters { get; protected set; }

        public virtual bool TryReadField(byte[] bytes, out string value)
        {
            value = null;
            if (Offset < 0 || (Offset + Length) >= bytes.Length)
            {
                return false;
            }

            value = Transform(Encoding.ASCII.GetString(bytes, Offset, Length));
            return true;
        }

        protected virtual string Transform(string value)
        {
            if (SpecialCharacters != null)
            {
                return value.Trim(SpecialCharacters);
            }
            else
            {
                return value.Trim();
            }
        }
    }
}
